package service

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"os"

	"github.com/taitan-org/talents"
)

type App struct {
	Name            string `json:"name"`
	Group           string `json:"group"`
	enableConfig    bool
	mainDir         string
	startDir        string
	configDir       string
	logDir          string
	appType         string
	initArgs        string
	killArgs        string
	killInstantArgs string
	needStarted     bool
	IsStarted       bool      `json:"is"`
	RestartTimes    int       `json:"rt"`
	LastStartTime   time.Time `json:"lst"`
	LastErrorLog    string    `json:"lel"`
	RelVer          string    `json:"rv"`
	ConfVer         string    `json:"cv"`
	inStarting      bool
}

var configs string
var apps string

var AppMap = make(map[string]*App)
var lock = &sync.RWMutex{}

var ip = talents.LocalIP()
var host, _ = os.Hostname()

func loadApps() {
	for k, app := range Conf.Client.Apps {
		appSlice := strings.Split(app, ",")
		if len(appSlice) != 8 {
			appSlice := strings.Split(app, Conf.Client.Sep)
			if len(appSlice) != 8 {
				Logger.Fatal("App配置不合法")
			}
		}

		ap := &App{}

		appN := strings.Split(appSlice[0], "/")[0]
		if k == 0 {
			apps = appN
		} else {
			apps = apps + "," + appN
		}

		ap.Name = appN
		ap.Group = appSlice[0]

		switch appSlice[1] {
		case "1":
			if k == 0 {
				configs = appSlice[0]
			} else {
				configs = configs + "," + appSlice[0]
			}
			ap.enableConfig = true
		case "0":
			ap.enableConfig = false
		default:
			Logger.Fatal("Config控制参数只能为0和1")
		}

		ap.mainDir = appSlice[2]

		if appSlice[3] == "." {
			ap.startDir = appSlice[2]
		} else {
			ap.startDir = appSlice[2] + "/" + appSlice[3]
		}

		if appSlice[4] == "." {
			ap.configDir = appSlice[2]
		} else {
			ap.configDir = appSlice[2] + "/" + appSlice[4]
		}

		if appSlice[5] == "." {
			ap.logDir = appSlice[2]
		} else {
			ap.logDir = appSlice[2] + "/" + appSlice[5]
		}

		ap.appType = appSlice[6]
		ap.initArgs = appSlice[7]

		AppMap[ap.Name] = ap
	}

	fmt.Println(apps, configs)
	for _, v := range AppMap {
		fmt.Printf("即将启动的app:%#v\n", v)
	}

	fmt.Println("本地ip: ", ip)
	fmt.Println("本地host: ", host)
}
